<?php
error_reporting(E_ALL ^ E_NOTICE);
ini_set('display_errors',1);
ini_set('memory_limit','128M');
set_time_limit(0);

$expected=array(
		'cmd'
	,	'api'
	,	'projectId'
	,	'type'
	,	'quickMode'
	,	'setAuthor'
	,	'setTaxa'
);

# Initialize allowed variables
foreach ($expected as $formvar)
	$$formvar = (isset(${"_$_SERVER[REQUEST_METHOD]"}[$formvar])) ? ${"_$_SERVER[REQUEST_METHOD]"}[$formvar]:NULL;

if (PHP_SAPI === 'cli') {

	function parseArgs($argv){
    array_shift($argv);
    $out = array();
    foreach ($argv as $arg){
        if (substr($arg,0,2) == '--'){
            $eqPos = strpos($arg,'=');
            if ($eqPos === false){
                $key = substr($arg,2);
                $out[$key] = isset($out[$key]) ? $out[$key] : true;
            } else {
                $key = substr($arg,2,$eqPos-2);
                $out[$key] = substr($arg,$eqPos+1);
            }
        } else if (substr($arg,0,1) == '-'){
            if (substr($arg,2,1) == '='){
                $key = substr($arg,1,1);
                $out[$key] = substr($arg,3);
            } else {
                $chars = str_split(substr($arg,1));
                foreach ($chars as $char){
                    $key = $char;
                    $out[$key] = isset($out[$key]) ? $out[$key] : true;
                }
            }
        } else {
            $out[] = $arg;
        }
    }
    return $out;
	}
	
	$args = (parseArgs($argv));
	if ($args) {
		foreach($args as $key => $value) {
			$$key = $value;
		}
	}
	
	include_once( dirname($_SERVER['PHP_SELF']) . '/../../config.php');

	$continue = true;
	$cFile = sys_get_temp_dir() . "/cron-reclassify-process-" . $cmd . ".pid";
	if (file_exists($cFile)) {
		$pid = file_get_contents($cFile);
		if (file_exists("/proc/$pid")) {
			$continue = false;
		} else {
		}
	}
	
	if (!$continue) exit();
	$cFileRef = fopen(sys_get_temp_dir() . "/cron-reclassify-process-" . $cmd . ".pid", "w");
	fputs($cFileRef, getmypid());
	fclose($cFileRef);
} else {
	include_once('../../config.php');
}

include_once($config['paths']['base'] . 'resources/api/classes/class.classify.php');

$classify = new Classify();
$valid = true;
header('Content-type: application/json');
switch($cmd) {

	case 'check':
		$timeStart = microtime(true);
		$projectId = trim($projectId);
		$type = strtoupper(trim($type));
		$type = (in_array($type,$config['stages'])) ? $type : 'NEW';
		$filter['filter'][] = array('data' => array('type' => 'string', 'comparison' => 'eq', 'value' => $type),'field' => 'stage');
		if(trim($projectId) != '') {
			$filter['filter'][] = array('data' => array('type' => 'string', 'comparison' => 'eq', 'value' => trim($projectId)),'field' => 'projectId');
		}
		$projects = $classify->project->getByFilter($filter);
		if(is_array($projects) && count($projects)) {
			foreach($projects as $project) {
				$valid = true; $code = 0;
				$classify->project->loadByProjectId($project->projectId);
				# process
				if(true == @fopen($classify->project->get('url'),"r")) {
					# downloading remote file to local directory structure
					$metaFilePath = $config['paths']['project'] . $project->projectId . '/';
					mkdir_recursive($metaFilePath);
# $source =  $metaFilePath . $project->projectId . '.' . pathinfo($classify->project->get('url'),PATHINFO_EXTENSION);
					$source =  $metaFilePath . $project->projectId . '.zip';
					if(!downloadRemoteFile($classify->project->get('url'), $source)) {
						$valid = false; $code = 108;
					} else {
						$classify->reclassify->set('sourcePath', $source);
						$classify->reclassify->set('projectId', $project->projectId);
						$classify->reclassify->set('metaFilePath', $metaFilePath);
						if($classify->reclassify->extractMetaFile()) {
							$classify->reclassify->getMetaFile();
							if(!$classify->reclassify->processCoreFile()) {
								$valid = false; $code = 103;
								if ($classify->reclassify->lineCount > 100000) {
									$code = 111;
								}
							}
						} else {
							$valid = false;$code = 109;
						}
					}
				} else {
					$valid = false;$code = 108;
				}

				if($valid) {
					$projectCount++;
					$classify->project->set('stage','LOADED');
					$classify->project->save();
				} else {
					$classify->project->set('stage','ERROR');
					$classify->project->set('comments',$classify->getError($code));
					$classify->project->save();
				}
			} # foreach projects
		} # if projects

		if ($valid) {
			print json_encode(array('success' => true, 'processTime' => (microtime(time) - $timeStart), 'projectCount' => $projectCount));
		} else {
			print json_encode(array('success' => false, 'error' => array('errorCode' => $code, 'errorMessage' => $classify->getError($code))));
		}
		break;

	case 'classify':
		$timeStart = microtime(true);
		$filter['filter'][] = array('data' => array('type' => 'string', 'comparison' => 'eq', 'value' => 'CLASSIFYING'),'field' => 'stage');
		if(trim($projectId) != '') {
			$filter['filter'][] = array('data' => array('type' => 'string', 'comparison' => 'eq', 'value' => trim($projectId)),'field' => 'projectId');
		}
		$filter['order'][] = array('field' => 'projectId', 'dir' => 'ASC');

		$projects = $classify->project->getByFilter($filter);
		if(is_array($projects) && count($projects)) {
			foreach($projects as $project) {
				$quickMode = ($project->quickMode == 1) ? true : false;
				if($classify->reclassify->classify($project->projectId, $quickMode)) {
					$projectCount++;
					$classify->project->loadByProjectId($project->projectId);
					$classify->project->set('stage','CLASSIFIED');
					$classify->project->save();
				}
			}
		}
		print json_encode(array('success' => true, 'processTime' => (microtime(time) - $timeStart), 'projectCount' => $projectCount));
		break;

	case 'archive':
		$timeStart = microtime(true);
		if($valid) {
			$filter['filter'][] = array('data' => array('type' => 'string', 'comparison' => 'eq', 'value' => 'ARCHIVING'),'field' => 'stage');
			$projects = $classify->project->getByFilter($filter);
			if(is_array($projects) && count($projects)) {
				foreach($projects as $project) {
					if($classify->reclassify->archive($project->projectId)) {
						$projectCount++;
						$classify->project->loadByProjectId($project->projectId);
						$classify->project->set('stage','ARCHIVED');
						$classify->project->save();
					}
				}
			}
			print json_encode(array('success' => true, 'processTime' => (microtime(time) - $timeStart), 'projectCount' => $projectCount));
		} else {
			print json_encode(array('success' => false, 'error' => array('errorCode' => $code, 'errorMessage' => $classify->getError($code))));
		}
		break;

	case 'cleanUp':
		$timeStart = microtime(true);
		$projectCount = 0;
		$days = 7;
		$ret = $classify->project->getCleanUpRecords($days);
		if (is_object($ret)) {
			while ($row = $ret->fetch_object()) {
				$path = $config['paths']['project'] . $row->projectId . '/';
				if(file_exists($path)) {
					recursiveDelete($path);
				}
				$classify->project->deleteProject($row->projectId);
				$projectCount++;
			}
		}
		
		print json_encode(array('success' => true, 'processTime' => (microtime(time) - $timeStart), 'projectCount' => $projectCount));
		break;

	default:
		print json_encode(array('No Task given'));
		break;
}

if (PHP_SAPI === 'cli') {
	unlink($cFile);
}
?>